package com.powernode.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.powernode.ex.handler.BusinessException;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 记录系统操作日志AOP
 */
@Component
@Aspect
@Slf4j
public class SysLogAspect {

    //切入点表达式
    public static final String POINT_CUT = "execution (* com.powernode.controller.*.*(..))";

    @Around(value = POINT_CUT)
    public Object logAround(ProceedingJoinPoint joinPoint){

        Object result = null;
        //1.获取请求对象（上下文）
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
           throw new BusinessException("出现未知错误，后端丢失上下文");
        }
        HttpServletRequest request = requestAttributes.getRequest();
        //获取请求路径
        String path = request.getRequestURI();
        //2.获取IP地址和请求参数
        String remoteHost = request.getRemoteHost();
        Object[] args = joinPoint.getArgs();
        //3.获取请求方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.toString();

        //4.获取目标方法上的ApiOperation注解
        ApiOperation apiOperation = method.getDeclaredAnnotation(ApiOperation.class);
        //5.判断注解对象是否为空
        String operation = "";
        if (apiOperation != null){
            //5.1.获取apiOperation注解的描述
            operation = apiOperation.value();
        }

        String finalArgs = "";
        //6.判断参数类型
        if (ObjectUtil.isEmpty(args) && args.length != 0 && args[0] instanceof MultipartFile){
            //6.1.说明当前参数是文件对象
            finalArgs = "file";
        }else {
            //将参数对象转为json
            finalArgs = JSONObject.toJSONString(apiOperation);
        }

        //7.记录开始时间
        long startTime = System.currentTimeMillis();
        try {
            //8.执行方法
            result = joinPoint.proceed(args);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        //9.记录结束时间
        long endTime = System.currentTimeMillis();
        long execTime = startTime - endTime;

        log.info("调用时间：{}，请求接口路径：{}，请求ip地址：{}，方法名称：{}，执行时长：{}，方法描述：{}",
                LocalDateTime.now(),path,remoteHost,methodName,execTime,operation);

        return result;
    }

}
